package io.kimmking.rpcfx.client;

import com.alibaba.fastjson.JSON;
import io.kimmking.rpcfx.api.Filter;
import io.kimmking.rpcfx.api.RpcfxRequest;
import io.kimmking.rpcfx.api.RpcfxResponse;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;

/**
 * @author lv
 * @date 2021/5/29 18:55
 */
public class CGLibProxy implements MethodInterceptor {
    public static final MediaType JSONTYPE = MediaType.get("application/json; charset=utf-8");
    private final Class<?> serviceClass;
    private final String url;
    private final Filter[] filters;
    public  CGLibProxy(Class serviceClass, String url,Filter... filters) {
        this.serviceClass = serviceClass;
        this.url = url;
        this.filters = filters;
    }
    public Object getInstance(Class claz) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(claz);
        // 回调方法
        enhancer.setCallback(this);
        // 创建代理对象
        return enhancer.create();
    }
    @Override
    public Object intercept(Object o, Method method, Object[] params, MethodProxy methodProxy) throws Exception {
        //return  methodProxy.invokeSuper(o,objects);
        //return method.getName();
        RpcfxRequest request = new RpcfxRequest();
        request.setServiceClass(this.serviceClass.getName());
        request.setMethod(method.getName());
        request.setParams(params);

        if (null!=filters) {
            for (Filter filter : filters) {
                if (!filter.filter(request)) {
                    return null;
                }
            }
        }
        RpcfxResponse response = post(request, url);
        if (!response.isStatus()){
            throw response.getException();
        }
        // 加filter地方之三
        // Student.setTeacher("cuijing");

        // 这里判断response.status，处理异常
        // 考虑封装一个全局的RpcfxException

        return JSON.parse(response.getResult().toString());
    }
    private RpcfxResponse post(RpcfxRequest req, String url) throws IOException, InterruptedException {
        String reqJson = JSON.toJSONString(req);
        System.out.println("req json: "+reqJson);

        return new HttpClient().start(url,reqJson);
    }

    public static void main(String[] args) throws MalformedURLException, InterruptedException {
        new HttpClient().start("http://127.0.0.1:8080","{\"method\":\"findById\",\"params\":[1],\"serviceClass\":\"io.kimmking.rpcfx.demo.api.UserService\"}");
    }
}
